package com.stkcall.library;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.provider.CallLog;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.PermissionChecker;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) company, All rights reserved.
 * <p>------------------------------------------------------
 *
 * @author: xujie
 * @date: 7/16/22
 */
public class CallListenerService extends Service {

    private static final String TAG = "CallListenerService";

    private PhoneStateListener phoneStateListener;
    private TelephonyManager telephonyManager;
    private String callNumber;
    private boolean isActive = false;
    private long duration = 0;//通话时长/s
    private ScheduledExecutorService executors = Executors.newScheduledThreadPool(5);

    private MyBinder binder = new MyBinder();
    public class MyBinder extends Binder{
        public CallListenerService getService(){
            return CallListenerService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();

        initPhoneStateListener();

    }

    /**
     * 初始化
     */
    private void initPhoneStateListener() {
        phoneStateListener = new PhoneStateListener() {
            @Override
            public void onCallStateChanged(int state, String incomingNumber) {
                super.onCallStateChanged(state, incomingNumber);
//                Toast.makeText(CallListenerService.this, "监听中...", Toast.LENGTH_SHORT).show();

                Log.d(TAG, "onCallStateChanged: " + state + incomingNumber);
                duration = 0;
                callNumber = incomingNumber;
                switch (state){
                    case TelephonyManager.CALL_STATE_IDLE:
                        executors.schedule(new Runnable() {
                            @Override
                            public void run() {
                                boolean callLogState = true;
                                if(CallPhoneManager.getInstance().isCall()) {
                                    Log.d(TAG, "isCall: ");
                                    callLogState = getCallLogState(CallPhoneManager.getInstance().getCallPhone());
                                }
                                if (isActive && callLogState) {
                                    CallPhoneManager.getInstance().updateState(CallListenerService.this, CallState.CALL_HANG_UP, callNumber,duration);
                                } else {
                                    CallPhoneManager.getInstance().updateState(CallListenerService.this, CallState.CALL_IDLE, callNumber,duration);
                                }
                                isActive = false;
                                CallPhoneManager.getInstance().resetIsCall();
                            }
                        },1, TimeUnit.SECONDS);

                        break;
                    case TelephonyManager.CALL_STATE_RINGING:
                        CallPhoneManager.getInstance().updateState(CallListenerService.this, CallState.CALL_IN,callNumber,duration);
                        break;
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        isActive = true;
                        CallPhoneManager.getInstance().updateState(CallListenerService.this, CallState.CALL_ACTIVE,callNumber,duration);
                        break;
                    default:
                        break;
                }
                
            }
        };

        // 设置来电监听器
        telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        }
    }

    /**
     * 获取拨打日志
     * @param number
     * @return
     */
    private boolean getCallLogState(String number) {
        boolean isLink = true;
        try {
            ContentResolver cr = getContentResolver();
            final Cursor cursor = cr.query(CallLog.Calls.CONTENT_URI,
                    new String[]{CallLog.Calls.NUMBER,CallLog.Calls.DATE,CallLog.Calls.TYPE,CallLog.Calls.DURATION},
                    CallLog.Calls.NUMBER + "=?",
                    new String[]{number},
                    CallLog.Calls.DATE + " desc");
            Log.d(TAG, "getCallLogState: cursor =" + cursor);

            if(cursor != null) {
                while (cursor.moveToNext()) {
                    String number1 = cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.NUMBER));
                    long durationTime = cursor.getLong(cursor.getColumnIndexOrThrow(CallLog.Calls.DURATION));
                    long date = cursor.getLong(cursor.getColumnIndexOrThrow(CallLog.Calls.DATE));
                    int type = cursor.getInt(cursor.getColumnIndexOrThrow(CallLog.Calls.TYPE));
                    Log.d(TAG, "getCallLogState: -----------------duration= " + durationTime + "date" + date + "type" + type + "number1"+number1);

                    if (durationTime > 0) {
                        duration = durationTime;
                        isLink = true;
                    } else {
                        isLink = false;
                    }
                    break;
                }
                cursor.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return isLink;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return false;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
    }
}
